var headers = {}
var body = ''
var url=''
var method=''
var res=''
var req={}
var id2req={}
function guid() {
	return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
		var r = Math.random() * 16 | 0,
			v = c == 'x' ? r : (r & 0x3 | 0x8);
		return v.toString(16);
	});
}
function checkHeaders() {
    err = ''
    headers = {}
    header = $('#headers').val()
    if (header.length == 0) {
        $('#headercheckres').text('无内容')
        return true
    } else {
        hs = header.replace('\r', '').replace('：', ':').split('\n')
        for (x = 0; x < hs.length; x++) {
            if (hs[x].length > 0) {
                h1 = hs[x].split(': ')
              
                if (h1.length == 2) {
                    headers[h1[0].trim()] = h1[1].trim()

                } else {
                    err += hs[x] + '格式不正确；'
                }
            }

        }
        if (err == '') {
            $('#headercheckres').text('正确')
            return true
        } else {
            $('#headercheckres').text(err)
            return false
        }

    }

}
function checkBody(istype) {
    err = ''
    body = ''
    bd = $('#body').val()
    if (bd.length == 0) {
        $('#checkbodyres').text('无内容')
        return true
    } else {
        bt = $('#bodytype').val()
        if (bt == 'Json') {
            try {
                json = JSON.parse(bd);
                body = JSON.stringify(json)
                if(istype){
                    jsshow = JSON.stringify(json, null, "\t")
                }else{
                    jsshow=body
                }
                
                
                $('#body').val(jsshow)
            } catch (error) {
                err = error

            }

        } else if (bt == 'Param') {
            body = bd
            b1 = bd.replace('\r','').replace('\n','').split('&')
            ss = ''
            for (x = 0; x < b1.length; x++) {
                if (b1[x].replace('\n','').length > 0) {
                    h1 = b1[x].split('=')
                    if (h1.length != 2) {
                        err += b1[x] + '格式不正确；'

                    }else{
                        if(ss!=''){
                            ss+='&'+b1[x]+'\n'
                        }else{
                            ss+=b1[x]+'\n'
                        }
                        
                    }
                }

            }
            if(istype){
                $('#body').val(ss)
            }else{
                $('#body').val(ss.replace('\n',''))
            }
            
        }else if(bt=='Text'){
            body = bd
        }else{
            body = bd
        }
        
        if (err == '') {
            $('#checkbodyres').text('正确')
            return true
        } else {
            $('#checkbodyres').text(err)
            return false
        }
    }

}
$('#checkheaders').click(
    checkHeaders)
$('#checkbody').click(function () {
   checkBody(true)
});

$('#bodynotype').click(function(){
    checkBody(false)
})
function go(is_go){
    r=checkHeaders()
    if(!r){
        alert('请求头格式错误')
    }
    r=checkBody(false)
    if(!r){
        alert('请求体格式错误')
    }
    method=$('#method').val()
    scheme=$('#scheme').val()
    url=$('#url').val()
    if(method=='POST'){
        if('Content-Type' in headers){

        }else{
            bt = $('#bodytype').val()
            if(bt=='Json'){
                headers['Content-Type']='application/json'
            }else if(bt=='Param'){
                headers['Content-Type']='application/x-www-form-urlencoded'
            }else if(bt=='Text'){
                headers['Content-Type']='text/plain'
            }
        }
    }
    if(url.toUpperCase().startsWith('HTTP')){

    }else{
        url=scheme+url
    }
    if(!is_go){
        return 0
    }
    var bgPage = chrome.extension.getBackgroundPage();
    try {
        bgPage.request(method,url,headers,body,function(a,b){
            ss=''
            console.log(a)
            if(a.readyState==4){
                ss+=a.responseURL+'\n'
                ss+='status:'+a.status+'\n'
                ss+='statusText:'+a.statusText+'\n'
                ss+=a.getAllResponseHeaders()+'\n\n'
                ss+=a.responseText
                res=ss
                $('#resp').html(ss)
            }
            
            
        })
    } catch (error) {
        res=error
        $('#resp').html(error)
    }
    
}
$('#go').click(function(){
    go(true)
})
$('#nohang').change(function(){
    if(this.checked){
        $('#resp').css('white-space','')
    }else{
        $('#resp').css('white-space','pre-line')
    }
    // console.log(this.checked)

})
// $('.shanchu').click(function(){
//     console.log($(this).parent().parent().parent().attr('id'))

//     $(this).parent().parent().parent().remove();
// })
$("#tbody").on("click", ".shanchu",function(){
    // console.log()
    idd=$(this).parent().parent().parent().attr('id')
    delete req[id2req[idd]]
    delete id2req[idd]
    $(this).parent().parent().parent().remove();
    chrome.storage.sync.set({ req:req }, function () {});
} );
$("#tbody").on("click", ".duqu",function(){
    // console.log()
    $('#shuoming').text('')
    idd=$(this).parent().parent().parent().attr('id')

    $('#method').val(req[id2req[idd]]['method']);
    u=req[id2req[idd]]['url']
    if(u=='暂存HTTPS' ||u=='暂存HTTP'){

    }else
    if(u.startsWith('HTTPS://') ||u.startsWith('https://')){
        $('#scheme').val('HTTPS://')
        $('#url').val(u.replace('HTTPS://','').replace('https://',''));
    }else{
        $('#scheme').val('HTTP://')
        $('#url').val(u.replace('HTTP://','').replace('http://',''));

    }

    

    ss=''
    for(x in req[id2req[idd]]['headers']){
        ss+=x+': '+req[id2req[idd]]['headers'][x]+'\n'
    }
    $('#headers').val(ss)
    $('#body').val(req[id2req[idd]]['body'])
    u=localStorage.getItem(req[id2req[idd]]['url'])
    if(u){
        $('#resp').html(u)
    }
    $('#shuoming').text('读取成功')
} );
chrome.storage.sync.get({ req:{} }, function (items) {
    req=items.req
    ss=''
    for(x in req){
        // i=guid()
        id2req[req[x]['id']]=x
        ss+='<tr id="'+req[x]['id']+'">    <td>'+req[x]['url']+'</td>    <td>'+req[x]['time']+'</td>    <td>      <div class="btn-group" style="float: right;">        <button type="button" class="btn duqu btn-link"          style="                    padding: 0px;                ">读取</button>        <button type="button" class="btn shanchu btn-link"          style="color: crimson; padding: 0px;margin-left: 10px;">删除</button></div>    </td>  </tr>'
    }
    $('#tbody').append(ss)

});
// prepend
$('#save').click(function(){
    var da = (new Date()).toLocaleString('chinese', { hour12: false })

    go(false)
    if(url=='HTTP://'){
        url='暂存HTTP'
    }else if(url=='HTTPS://'){
        url='暂存HTTPS'
    }
    
    if(url in req){
        rid=req[url]['id']
        delete id2req[rid]
        delete req[url]
        $('#'+rid).remove()
        
    }
    i=guid()
    req[url]={method:method,url:url,headers:headers,body:body,time:da,id:i}
    localStorage.setItem(url,res)

    id2req[i]=url

    
    
    chrome.storage.sync.set({ req:req }, function () {
        
        $('#tbody').prepend('<tr id="'+i+'">    <td>'+url+'</td>    <td>'+da+'</td>    <td>      <div class="btn-group" style="float: right;">        <button type="button" class="btn duqu btn-link"          style="                    padding: 0px;                ">读取</button>        <button type="button" class="btn shanchu btn-link"          style="color: crimson; padding: 0px;margin-left: 10px;">删除</button></div>    </td>  </tr>')
        
    });
    // $('#tbody').append('<tr id="'+guid()+'">    <td>https://paytest.ciicsh.com/auth/authenticate/login?1231313123123123</td>    <td>2020-02-05 12:25:54</td>    <td>      <div class="btn-group" style="float: right;">        <button type="button" class="btn duqu btn-link"          style="                    padding: 0px;                ">读取</button>        <button type="button" class="btn shanchu btn-link"          style="color: crimson; padding: 0px;margin-left: 10px;">删除</button></div>    </td>  </tr>')
})